package com.witmore.neutron.ai.web.wechat.service;

import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.env.Environment;
import org.springframework.http.HttpEntity;
import org.springframework.http.ResponseEntity;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestTemplate;

import java.util.List;

/**
 * 微信消息转发服务
 * Author: 豆子高
 * Date: 2025/12/19
 */
@Slf4j
@Service
public class WechatForwardService {

    @Autowired
    private Environment environment;

    /**
     * 异步转发微信回调消息到其他环境
     *
     * @param xmlContent 微信回调消息的XML内容
     */
    @Async("taskExecutor")
    public void forwardToOtherEnvironments(String xmlContent) {
        // 检查当前环境，只有生产环境才执行转发
        String[] activeProfiles = environment.getActiveProfiles();
        boolean isProdEnvironment = false;
        for (String profile : activeProfiles) {
            if ("prod".equals(profile)) {
                isProdEnvironment = true;
                break;
            }
        }

        if (!isProdEnvironment) {
            log.info("当前环境为非生产环境，跳过微信回调消息转发");
            return;
        }

        log.info("开始异步转发微信回调消息到其他环境");

        // 获取需要转发的目标环境URL列表（可以从配置文件中读取）
        List<String> targetUrls = List.of(
                "https://ai-beta.witmore.cn/wechat/callback",
                "http://121.40.41.167:8097/wechat/callback"
        );

        // 异步转发
        targetUrls.forEach(url -> {
            try {
                // 转发请求
                RestTemplate restTemplate = new RestTemplate();
                HttpEntity<String> entity = new HttpEntity<>(xmlContent);
                ResponseEntity<String> response = restTemplate.postForEntity(url, entity, String.class);

                log.info("转发到 {} 成功，响应: {}", url, response.getBody());
            } catch (Exception e) {
                log.error("转发到 {} 失败", url, e);
            }
        });

        log.info("异步转发微信回调消息完成");
    }
}
